package com.xyy.ec.qualification.executor.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.xyy.ec.qualification.config.ConfigManagerService;
import com.xyy.ec.qualification.utils.SQLExecuteUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.ResultSetMetaData;
import java.util.*;

/**
 * 数据库执行器
 */
@Slf4j
public class DbSqlManager {

    private static final Logger logger = LoggerFactory.getLogger(DbSqlManager.class);


    public static String genSQL(String sql, String field,List<String> erpCodes) {
        //拼接sql
        StringBuilder sb = new StringBuilder();
        sb.append("select de.* from ( ")
                .append(sql)
                .append(" ) de ");

        String  queryCriteria = queryCriteria(field, erpCodes);
        if(StringUtils.isNotEmpty(queryCriteria)){
            sb.append(" ").append(queryCriteria);
        }
        return sb.toString();
    }

    /**
     * 查询条件
     *
     * @param erpCodes
     * @return
     */
    private static String queryCriteria(String field,List<String> erpCodes) {
        if (StringUtils.isBlank(field) || CollectionUtils.isEmpty(erpCodes)) {
            return "";
        }
        StringBuilder where = new StringBuilder();
        where.append(" where ").append(field).append(" in ").append("(");
        for (String param : erpCodes) {
            where.append("'").append(param).append("',");
        }
        where.deleteCharAt(where.length() - 1);
        where.append(")");
        return where.toString();
    }

    /**
     * 查询数据
     *
     * @param sql    sql查询
     * @param values 值
     * @return
     */
    public static List<Map<String, Object>> quereyData(String sql, List<Object> values) {
        DruidDataSource druidDataSource = ConfigManagerService.getDataSource();
        List<Map<String, Object>> list = (List<Map<String, Object>>) SQLExecuteUtil.sqlRS(druidDataSource, sql, values, rs -> {
            List<Map<String, Object>> rows = new ArrayList<>();

            try {
                ResultSetMetaData metaData = rs.getMetaData();
                Integer columnCount = metaData.getColumnCount();

                while (rs.next()) {
                    Map<String, Object> row = new HashMap<>();

                    for (int i = 1; i <= columnCount; i++) {
                        row.put(metaData.getColumnLabel(i).toLowerCase(), rs.getObject(i));
                    }

                    rows.add(row);
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                rows = null;
            }
            return rows;
        });

        if (list == null) {
            logger.error("sql语句执行异常:{}", sql);
            //抛出异常，禁止try-catch
            throw new RuntimeException("查询语句执行异常，请稍后重试。");
        }

        return list;
    }

}
